import React, { useState, Key, useEffect } from "react";
import { useNavigate } from "react-router";
import {
  Card,
  Button,
  Form,
  Input,
  Table,
  Space,
  Tooltip,
  message,
} from "antd";
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import type { HospitalSetItem } from "@/api/hospital/hospitalSet/model/hospitalSetTypes";

import {
  reqGetHospitalSet,
  reqBatchRemove,
  reqRemoveHospitalSetById,
} from "@/api/hospital/hospitalSet/index";
import type { HospitalSetList } from "@/api/hospital/hospitalSet/model/hospitalSetTypes";

// 查询是否有筛选数据
let flag = false;
function HospitalSet() {
  const navigate = useNavigate();
  // 获取form实例
  const [form] = Form.useForm();
  // 分页数据
  const [pageSize, setPageSize] = useState(5);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [hospitalSetList, setHospitalSetList] = useState<HospitalSetList>([]);

  // 处理批量删除按钮是否禁用的状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);

  // 获取分页列表
  const getHospitalSetList = async (page: number, pageSize: number) => {
    let res;
    if (flag) {
      // 1. 利用Form.useForm创建form实例
      // 2. 用form实例和对应的Form组件进行绑定 form.Item 必须要name属性
      // 3. form.getFieldsValues() 返回表单中的所有数据
      const { hosname, hoscode } = form.getFieldsValue();
      // console.log(hosname, hoscode);

      res = await reqGetHospitalSet(page, pageSize, hosname, hoscode);
    } else {
      res = await reqGetHospitalSet(page, pageSize);
    }
    // console.log(res);
    setHospitalSetList(res.records);
    setTotal(res.total);
  };
  // 行
  const columns: ColumnsType<HospitalSetItem> = [
    {
      title: "序号",
      align: "center",
      width: 80,
      render(text, record, index) {
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编码",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机号",
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      dataIndex: "action",
      fixed: "right",
      width: 100,
      // 当前行的值，当前行数据，行索引
      render(_, record) {
        // 处理批量删除按钮是否禁用的状态
        // const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])
        return (
          <Space size="middle">
            <Tooltip placement="top" title="修改医院">
              <Button
                icon={<EditOutlined />}
                type="primary"
                size="middle"
                onClick={() => {
                  navigate("/syt/hospital/hospitalSet/update", {
                    state: record.id,
                  });
                }}
              ></Button>
            </Tooltip>
            <Tooltip placement="top" title="删除医院">
              <Button
                icon={<DeleteOutlined />}
                type="primary"
                danger
                size="middle"
                onClick={async () => {
                  const id = record.id;
                  await reqRemoveHospitalSetById(id as number);
                  message.success("删除医院设置成功");
                  getHospitalSetList(page, pageSize);
                }}
              ></Button>
            </Tooltip>
          </Space>
        );
      },
    },
  ];

  // 相当于 componentDidMount 和 componentDidUpdate:
  // 第二个参数是[]，表示只挂载完
  useEffect(() => {
    getHospitalSetList(page, pageSize);
  }, []);
  // 查询
  const onFinish = () => {
    flag = true;
    getHospitalSetList(1, pageSize);
    setPage(1);
  };
  // 清空
  const clear = () => {
    flag = false;
    form.setFieldsValue({ hosname: undefined, hoscode: undefined });
    getHospitalSetList(1, pageSize);
    setPage(1);
  };

  return (
    <Card style={{ minHeight: "calc(100vh - 64px)" }}>
      {/*layout 布局 横排 onValuesChange 字段值更新时触发回调事件 onFinish 提交表单且数据验证成功后回调事件*/}
      <Form
        style={{ maxWidth: 600 }}
        layout="inline"
        onValuesChange={(changedValues, allValues) => {
          // console.log(changedValues, allValues);

          flag = false;
        }}
        onFinish={onFinish}
        form={form}
        name="hosform"
      >
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编码" />
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            icon={<SearchOutlined />}
            style={{ marginRight: 10 }}
            htmlType="submit"
          >
            查询
          </Button>
          <Button type="default" onClick={clear}>
            清空
          </Button>
        </Form.Item>
      </Form>
      <div style={{ marginTop: 20, marginBottom: 20 }}>
        {/* useNavigate 返回一个函数用来编程式导航 */}
        <Button
          type="primary"
          style={{ marginRight: 10 }}
          onClick={() => {
            navigate("/syt/hospital/hospitalSet/add");
          }}
        >
          添加
        </Button>
        {/* 批量删除 */}
        {/* 如果key数组的长度为0，表示没有选中项 显示禁用效果*/}
        <Button
          type="primary"
          danger
          disabled={!selectedRowKeys.length}
          onClick={async () => {
            console.log(111);
            const res = await reqBatchRemove(selectedRowKeys);
            console.log(res);
            message.success("批量删除成功");
            getHospitalSetList(page, pageSize);
          }}
        >
          批量删除
        </Button>
      </div>
      {/* 
      rowSelection 复选框 onChange选中项发生变化时的回调
      scroll={{ x: 1300 }} 滚动
      pagination 分页器

      */}
      <Table
        dataSource={hospitalSetList}
        columns={columns}
        bordered
        scroll={{ x: 1300 }}
        rowKey={"id"}
        pagination={{
          total,
          current: page,
          pageSize,
          showTotal(total, render) {
            return `共${total}条`;
          },
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15, 20],
          onChange(page, pageSize) {
            // console.log(page, pageSize);
            setPageSize(pageSize);
            setPage(page);
            getHospitalSetList(page, pageSize);
          },
        }}
        rowSelection={{
          onChange(selectedRowKeys) {
            console.log(selectedRowKeys);
            // 指定选中项的 key 数组，需要和 onChange 进行配合
            setSelectedRowKeys(selectedRowKeys);
          },
        }}
      />
      ;
    </Card>
  );
}

export default HospitalSet;
